#include "Heap.h"

void Swap(int* p1, int* p2)
{
	int tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void HeapInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = php->size = 0;
}

void HeapPrint(HP* php)
{
	assert(php);
	for (int i = 0; i < php->size; i++)
	{
		printf("%d ", php->a[i]);
	}
	printf("\n");
}

void HeapDestory(HP* php)
{
	assert(php);
	free(php->a);
	php->size = php->capacity = 0;
}

void AdjustUp(HPDateType* a, int child)
{
	int parent = (child - 1) / 2;
	while(child > 0)
	{ 
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(HP* php, HPDateType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		int* tmp = (int*)realloc(php->a,sizeof(int) * newcapacity);
		if (tmp == NULL)
		{
			perror("HeapPush::realloc");
			return;
		}
		php->a = tmp; 
		php->capacity = newcapacity;
	}

	php->a[php->size] = x;
	php->size++;
	AdjustUp(php->a,php->size - 1);
}

void AdjustDown(HPDateType* a,int size,int parent)
{
	//int parent = 0;
	//int leftchild = parent * 2 + 1;
	//int rightchild = parent * 2 + 2;
	//int smallchild = leftchild;
	//int bigchild = rightchild;
	//if (a[leftchild] > a[rightchild])
	//{
	//	smallchild = rightchild;
	//	bigchild = leftchild;
	//}
	//while (smallchild < size)
	//{
	//	if (a[parent] > a[smallchild])
	//	{
	//		Swap(&a[parent], &a[smallchild]);
	//		parent = smallchild;
	//		leftchild = parent * 2 + 1;
	//		rightchild = parent * 2 + 2;
	//		smallchild = leftchild;
	//		bigchild = rightchild;
	//		if (a[leftchild] > a[rightchild])
	//		{
	//			smallchild = rightchild;
	//			bigchild = leftchild;
	//		}
	//	}
	//	else
	//	{
	//		break;
	//	}
	//}
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child + 1 < size && a[child + 1] < a[child])
		{
			++child;
		}

		if (a[child] < a[parent] )
		{
			Swap(&a[parent], &a[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPop(HP* php)
{
	assert(php);
	assert(php->size > 0);
	Swap(&(php->a[0]), &(php->a[php->size - 1]));
	php->size--;
	AdjustDown(php->a,php->size,0);
}

HPDateType HeapTop(HP* php)
{
	assert(php);
	return php->a[0];
}

bool HeapEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}

int HeapSize(HP* php)
{
	assert(php);
	return php->size;
}
